<?php

/* 
 * 函数集合
 * @2015-12-22 wzl
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * 读取配置表的参数 data_config/config_params.php
 * @param string $parent 父节点
 * @param string $son 子节点
 * @param string $grandchild 孙节点
 */
function get_config_params($parent, $son = '' , $grandchild = '') {
    $data = include(APP_PATH . "data_config/config_params.php");
    if(isset($data[$parent]) && is_array($data)) {
        $parent = $data[$parent];
        if(isset($parent[$son]) && is_array($parent)){
            $son = $parent[$son];
            if(isset($son[$grandchild]) && is_array($son)){
                return $son[$grandchild];
            }
            return $son;
        }
        return $parent;
    }
    return "";
}
/**
 * 读取活动配置表的参数 data/config_actives.php
 * @param string $parent 父节点
 * @param string $son 子节点
 * @param string $grandchild 孙节点
 */
function get_config_actives($parent, $son = '' , $grandchild = '') {
    $data = include(APP_PATH . "data_config/config_actives.php");
    if(isset($data[$parent]) && is_array($data)) {
        $parent = $data[$parent];
        if(isset($parent[$son]) && is_array($parent)){
            $son = $parent[$son];
            if(isset($son[$grandchild]) && is_array($son)){
                return $son[$grandchild];
            }
            return $son;
        }
        return $parent;
    }
    return "";
}
/**
 * 读取活动配置表的参数 data/config_actives.php
 * @param string $parent 父节点
 * @param string $son 子节点
 * @param string $grandchild 孙节点
 */
function get_config_api($parent, $son = '' , $grandchild = '') {
    $data = include(APP_PATH . "data_config/config_api.php");
    if(isset($data[$parent]) && is_array($data)) {
        $parent = $data[$parent];
        if(isset($parent[$son]) && is_array($parent)){
            $son = $parent[$son];
            if(isset($son[$grandchild]) && is_array($son)){
                return $son[$grandchild];
            }
            return $son;
        }
        return $parent;
    }
    return "";
}
/**
 * 读结果缓存文件
 *
 * @params  string  $cache_name
 *
 * @return  array   $data
 */
function read_static_cache($cache_name)
{
    if(APP_DEBUG) {
        return false;
    }
    static $result = array();
    if (!empty($result[$cache_name]))
    {
        return $result[$cache_name];
    }

    $cache_file_path = TEMP_PATH . $cache_name . '.php';

    if (file_exists($cache_file_path))
    {
        include_once($cache_file_path);
        $result[$cache_name] = $data;
        return $result[$cache_name];
    }
    else
    {
        return false;
    }
}

/**
 * 写结果缓存文件
 *
 * @params  string  $cache_name
 * @params  string  $caches
 *
 * @return
 */
function write_static_cache($cache_name, $caches)
{
    $cache_file_path = TEMP_PATH . $cache_name . '.php';
    $content = "<?php\r\n";
    $content .= "\$data = " . var_export($caches, true) . ";\r\n";
    $content .= "?>";
    file_put_contents($cache_file_path, $content, LOCK_EX);
    chmod($cache_file_path, 0777);
}

/**
 * 密码加密
 * @param string $user_pass 用户密码
 * @param string $salt 干扰码
 * @param string $node [可选]密钥节点，config_params配置key 
 * @return string 加密后的密码
 */
function pass_encrypt($user_pass, $salt, $node = 'pass_key'){
    $key = get_config_params('key', $node);
    return md5($user_pass . md5($salt . $key));
}
/**
 * 设置cookie
 * @param string $key 键
 * @param string $value 值
 * @param int $second 默认60秒
 */
function setCookies($key, $value, $second = 60) {
    $expire = time() + $second;
    setcookie($key, $value, $expire, '/');
}
/**
 * 获取cookie
 * @param string $key 键
 * @return boolean|string 返回结果
 */
function getCookies($key) {
    if(isset($_COOKIE[$key])) {
        return $_COOKIE[$key];
    }
    return false;
}
/**
 * 获取当前时间
 * @return type
 */
function p_getTime(){
    date_default_timezone_set('PRC');
    return time();
}
/**
 * 字符串时间格式转换成时间戳
 * @param string $strTime 字符串
 * @return int 时间戳
 */
function p_str2time($strTime){
    date_default_timezone_set('PRC');
    return strtotime($strTime);
}
/**
 * 
 * @param int $time 时间戳
 * @param string $format 可选 格式
 * @return string 转换成字符串时间格式
 */
function p_time2str($time, $format = 'Y-m-d H:i:s') {
    date_default_timezone_set('PRC');
    if($time > 0) {
        return date($format, $time);
    }
    return '';    
}
/**
* 获取URL 参数值
* @param string $url 完整的URL
* @param string $key 参数KEY
* @return string 返回参数的值
*/
function p_getUrlParams($url, $key) {
   $result = array();
   $arr = parse_url($url);
   $params = $arr['query'];
   parse_str($params, $result);
   return $result[$key];
}
/**
 * 截取字符串
 * @param string $string 需要截取的字符串
 * @param int $sublen 截取長度
 * @param int $start 開始位置，默認為0
 * @param string $code 編碼，默認UTF-8
 * @return string 返回截取結果
 */
function p_cut_str($string, $sublen, $start = 0, $code = 'UTF-8'){
    if($code == 'UTF-8') {
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);
        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen));
        return join('', array_slice($t_string[0], $start, $sublen));
    }else{
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr = '';
        for($i=0; $i< $strlen; $i++){
            if($i>=$start && $i< ($start+$sublen)){
                if(ord(substr($string, $i, 1))>129){
                    $tmpstr.= substr($string, $i, 2);
                }
                else{
                    $tmpstr.= substr($string, $i, 1);
                }
            }
            if(ord(substr($string, $i, 1))>129) $i++;
        }
        return $tmpstr;
    }
}

/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function p_real_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}

/**
 * 计算字符串的长度（汉字按照两个字符计算）
 *
 * @param   string      $str        字符串
 *
 * @return  int
 */
function p_str_len($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

    if ($length)
    {
        return strlen($str) - $length + intval($length / 3) * 2;
    }
    else
    {
        return strlen($str);
    }
}

/**
 * 递归方式的对变量中的特殊字符进行转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function addslashes_deep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
        return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
    }
}

/**
 * 将对象成员变量或者数组的特殊字符进行转义
 *
 * @access   public
 * @param    mix        $obj      对象或者数组
 * @author   Xuan Yan
 *
 * @return   mix                  对象或者数组
 */
function addslashes_deep_obj($obj)
{
    if (is_object($obj) == true)
    {
        foreach ($obj AS $key => $val)
        {
            $obj->$key = addslashes_deep($val);
        }
    }
    else
    {
        $obj = addslashes_deep($obj);
    }

    return $obj;
}

/**
 * 递归方式的对变量中的特殊字符去除转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function stripslashes_deep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
        return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    }
}

/**
 *  将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
 *
 * @access  public
 * @param   string       $str         待转换字串
 *
 * @return  string       $str         处理后字串
 */
function p_make_semiangle($str)
{
    $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
                 '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
                 'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
                 'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
                 'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
                 'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
                 'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
                 'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
                 'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
                 'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
                 'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
                 'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
                 'ｙ' => 'y', 'ｚ' => 'z',
                 '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
                 '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
                 '‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',
                 '》' => '>',
                 '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
                 '：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
                 '；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
                 '”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',
                 '　' => ' ');

    return strtr($str, $arr);
}
/**
 * 过滤用户输入的基本数据，防止script攻击
 *
 * @access      public
 * @return      string
 */
function p_compile_str($str)
{
    $arr = array('<' => '＜', '>' => '＞');

    return strtr($str, $arr);
}

/**
 * 获取服务器的ip
 *
 * @access      public
 *
 * @return string
 **/
function p_real_server_ip()
{
    static $serverip = NULL;

    if ($serverip !== NULL)
    {
        return $serverip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['SERVER_ADDR']))
        {
            $serverip = $_SERVER['SERVER_ADDR'];
        }
        else
        {
            $serverip = '0.0.0.0';
        }
    }
    else
    {
        $serverip = getenv('SERVER_ADDR');
    }

    return $serverip;
}
function p_SafeFilter(&$arr)  {          
        $ra=Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','/script/','/javascript/','/vbscript/','/expression/','/applet/','/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/title/','/bgsound/','/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/','/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/','/onmouseout/','/onmouseover/','/onmouseup/','/onunload/');
        if (is_array($arr))    {      
            foreach ($arr as $key => $value){         
                if (!is_array($value)){           
                    if (!get_magic_quotes_gpc())//不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。           
                    { 
                        $value  = addslashes($value);//给单引号（'）、双引号（"）、反斜线（\）与 NUL（NULL 字符）加上反斜线转义           
                    }           
                    $value       = preg_replace($ra, '', $value);     //删除非打印字符，粗暴式过滤xss可疑字符串           
                    $arr[$key]     = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体         
                }else{          
                    p_SafeFilter($arr[$key]);  
                }     
            }    
        } 
    }